using AvaVSExt.Attributes;
using AvaVSExt.Helpers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace AvaVSExt
{
    public partial class Program
    {
        [VSCommand("xmlns")]
        public static void GetXmlns()
        {
            var info = VSHelper.GetSelectedItemInfoInSolutionExplorerCs();
            if (info is null) return;
            if (info.ItemType != ItemType.File) return;
            Xmlns.GetXmlnsToClipboard(info.ItemFullPath);
        }
    }

    public class Xmlns
    {
        public static string GetXmlns(string csfile)
        {
            var namespaceNames = GetNamespacesFromFile(csfile);

            var sb = new StringBuilder();

            foreach (var namespaceName in namespaceNames)
            {
                //Console.WriteLine(namespaceName);
                var namespaceUsing = GetNamespaceUsing(namespaceName);
                sb.AppendLine(namespaceUsing);
            }
            return sb.ToString();
        }

        public static void GetXmlnsToClipboard(string csfile)
        {
            var result = GetXmlns(csfile);
            Clipboard.SetText(result);
        }

        private static string GetNamespaceUsing(string namespaceName)
        {
            var shortName = GetNamespaceShortName(namespaceName);
            return $"xmlns:{shortName}=\"using:{namespaceName}\"";
        }

        /// <summary>
        /// 获得命名空间的短名。
        /// </summary>
        /// <param name="namespaceName"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        public static string GetNamespaceShortName(string namespaceName)
        {
            if (string.IsNullOrWhiteSpace(namespaceName)) throw new ArgumentNullException("命名空间为空");
            var prefixIndex = namespaceName.IndexOf('.');
            if (prefixIndex == -1) return "app"; // 找不到子内容时

            var specialNames = new string[] { "viewmodel", "viewmodels", "view", "views", "models", "model", "entities", "entity" };

            var stack = new Stack<string>();

            var parts = namespaceName.Split('.');

            foreach (var part in parts.Skip(1))
            {
                var lowerPart = part.ToLower();
                if (specialNames.Contains(lowerPart)) stack.Clear();
                stack.Push(lowerPart);
            }

            return string.Join("-", stack.ToArray());

        }

        private static List<string> GetNamespacesFromFile(string file)
        {
            using (var fs = File.OpenRead(file))
            {
                using (var reader = new StreamReader(fs))
                {
                    return GetNamespacesFromStringReader(reader);
                }
            }
        }
        private static List<string> GetNamespacesFromStringReader(StreamReader reader)
        {
            var result = new List<string>();
            while (reader.EndOfStream == false)
            {
                var line = reader.ReadLine();
                if (IsNamespaceDeclare(line))
                {
                    var namespaceName = ExtractNamespaceNameFromDeclare(line);
                    result.Add(namespaceName);
                }
            }

            return result;
        }
        private static bool IsNamespaceDeclare(string code)
        {
            if (string.IsNullOrWhiteSpace(code)) return false;
            if (code.StartsWith("namespace")) return true;
            return false;
        }
        private static string ExtractNamespaceNameFromDeclare(string code)
        {
            return code.Replace(";", string.Empty).Split().Last();
        }
    }
}
